package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private AddressMapper addressMapper;

    /**
     * 提交订单
     * @param order
     */
    @Override
    public void save(Order order) {
        //获取用户
        User user = UserHolder.get();
        //获取购物车信息
        List<Cart> cartList = cartService.findAll();
        //判断购物车是否为空
        if (CollectionUtil.isEmpty(cartList)){
            throw new CustomException("购物车不存在!");
        }
        //获取收货地址
        Address address = addressMapper.selectById(order.getAddressId());
        //判断收货地址是否为空
        if (address==null){
            throw new CustomException("您没有收货地址,无法提交订单");
        }
        //生成订单id备用
        long orderId = IdWorker.getId();
        //设置总金额
        BigDecimal total = new BigDecimal(0);
        //遍历购物车,生成订单详情
        for (Cart cart : cartList) {
            //创建订单详情对象
            OrderDetail orderDetail = new OrderDetail();
            //使用spring提供的BeanUtils复制购物车信息
            //值一为,原始对象,值二为,目标对象,值三为,不需要复制的属性
            BeanUtils.copyProperties(cart,orderDetail,new String[]{"id","userId"});
            //给订单详情设置订单的id
            orderDetail.setOrderId(orderId);
            //插入订单详情数据
            orderDetailMapper.insert(orderDetail);
            //计算金额,总金额=单个菜品的金*数量
            total= total.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }
        //准备订单数据
        order.setId(orderId);
        order.setUserId(user.getId());
        order.setNumber(String.valueOf(orderId));
        order.setStatus(1);//待付款
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());//付款时间
        order.setAmount(total);
        //插入订单
        orderMapper.insert(order);
        //清空购物车
        cartService.clean();
    }

    /**
     * 分页查询订单记录
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<Order> findPage(Integer pageNum, Integer pageSize) {
        //创建分页查询对象
        Page<Order> page = new Page<>(pageNum, pageSize);
        //设置订单查询条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, UserHolder.get().getId());
        wrapper.orderByDesc(Order::getOrderTime);
        //查询
        page = orderMapper.selectPage(page, wrapper);

        //获取结果集
        List<Order> orderList = page.getRecords();
        for (Order order : orderList) {
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            //设置条件为订单的id,根据订单id查询订单详情结果
            wrapper1.eq(OrderDetail::getOrderId,order.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper1);
            order.setOrderDetails(orderDetails);
        }
        //返回分页结果
        return page;
    }

    /**
     * 管理端订单查询
     * @param pageNum
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Page<Order> findPageOrder(Integer pageNum, Integer pageSize, String number, String beginTime, String endTime) {
        //创建分页对象
        Page<Order> page = new Page<>(pageNum,pageSize);
        //创建查询条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        //设置条件为如果有订单号，就用订单号精确查询
        wrapper.eq(StringUtils.isNotEmpty(number),Order::getNumber,number);
        //如果选择时间就按照时间查询
        wrapper.between(beginTime!=null && endTime!=null,Order::getOrderTime,beginTime,endTime);
        //查询
        page = orderMapper.selectPage(page, wrapper);
        //取出结果集中的订单集合
        List<Order> orderList = page.getRecords();
        //遍历每个订单
        for (Order order : orderList) {
            //创建订单详情查询条件
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId,order.getId());
            //查询订单详情
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper1);
            //将查询到的订单详情赋值给订单
            order.setOrderDetails(orderDetails);
        }

        return page;
    }
}
